import config from '@/request/baseUrl.js';

// 转换服务器图片
export const webSrc = (src) => {
	return config.baseUrl + src
}

// 登录验证
export const author = (fn) => {
	if (uni.getStorageSync("TOKEN")) {
		fn();
	} else {
		uni.$emit('Authorize', Number(new Date()));
	}
}

// 跳转商城客服
// export const toChat = (shopId, info = null) => {
// 	uni.navigateTo({
// 		url: info ? `/pages/mall/goodsServer?shop_id=${shopId}&goods=${JSON.stringify(info)}` :
// 			`/pages/mall/goodsServer?shop_id=${shopId}`
// 	});
// }

// 保存聊天记录
export const setChat = (data, send) => {
	let uid = send == 'send' ? data.to_id : data.form.id;
	uni.getStorage({
		key: 'wanlchat:message_' + uid,
		success: (res) => {
			// 储存所有消息
			// 优化,只储存 100条数据,超过100条,通过接口获取历史记录
			let arr = res.data.slice(-96);
			arr.push(data);
			uni.setStorageSync('wanlchat:message_' + uid, arr);
		},
		fail: () => {
			uni.setStorageSync('wanlchat:message_' + uid, [data]);
		}
	});
	// 返回原始数据
	return data;
}

// IM时间友好
export const timeToChat = (timestamp = null) => {
	if (timestamp == null) timestamp = Number(new Date());
	timestamp = parseInt(timestamp);
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 10) timestamp *= 1000;
	var timer = (new Date()).getTime() - timestamp;
	timer = parseInt(timer / 1000);
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	let tips = '';
	switch (true) {
		case timer < 86400:
			tips = timeFormat(timestamp, 'hh:MM');
			break;
		case timer >= 86400 && timer < 86400 * 7:
			var now = new Date(timestamp);
			var week = ['日', '一', '二', '三', '四', '五', '六'];
			switch (new Date().getDate() - now.getDate()) {
				case 1:
					tips = timeFormat(timestamp, '昨天 hh:MM');
					break;
				case 2:
					tips = timeFormat(timestamp, '前天 hh:MM');
					break;
				default:
					tips = '星期' + week[now.getDay()] + timeFormat(timestamp, 'hh:MM');
			}
			break;
		case timer >= 86400 * 7:
			tips = timeFormat(timestamp, 'mm-dd hh:MM');
			break;
		default:
			tips = timeFormat(timestamp, 'yyyy-mm-dd hh:MM');
	}
	return tips;
}

/**
 * 社交时间友好
 */
export const timeToDate = (timestamp = null, format = 'yyyy-mm-dd') => {
	if (timestamp == null) timestamp = Number(new Date());
	timestamp = parseInt(timestamp);
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 10) timestamp *= 1000;
	var timer = (new Date()).getTime() - timestamp;
	timer = parseInt(timer / 1000);
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	let tips = '';
	switch (true) {
		case timer < 300:
			tips = '刚刚';
			break;
		case timer >= 300 && timer < 3600:
			tips = parseInt(timer / 60) + '分钟前';
			break;
		case timer >= 3600 && timer < 86400:
			tips = parseInt(timer / 3600) + '小时前';
			break;
		case timer >= 86400 && timer < 2592000:
			tips = parseInt(timer / 86400) + '天前';
			break;
		default:
			// 如果format为false，则无论什么时间戳，都显示xx之前
			if (format === false) {
				if (timer >= 2592000 && timer < 365 * 86400) {
					tips = parseInt(timer / (86400 * 30)) + '个月前';
				} else {
					tips = parseInt(timer / (86400 * 365)) + '年前';
				}
			} else {
				tips = timeFormat(timestamp, format);
			}
	}
	return tips;
}

// 时间格式化
export const timeFormat = (timestamp = null, fmt = 'yyyy-mm-dd') => {
	// 其他更多是格式化有如下:
	// yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
	timestamp = parseInt(timestamp);
	// 如果为null,则格式化当前时间
	if (!timestamp) timestamp = Number(new Date());
	// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
	if (timestamp.toString().length == 10) timestamp *= 1000;
	let date = new Date(timestamp);
	let ret;
	let opt = {
		"y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"h+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"s+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}

// 获取本地缓存
export const getStorage = (name) => {
	let data = uni.getStorageSync(name);
	return data ? JSON.parse(data) : '';
}

//  获取上级页面栈
export const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	// #ifndef H5
	return prePage.$vm;
	// #endif
}

// 加法精度计算
export const bcadd = (a, b) => {
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length
	} catch (f) {
		c = 0
	}
	try {
		d = b.toString().split(".")[1].length
	} catch (f) {
		d = 0
	}
	return e = Math.pow(10, Math.max(c, d)), (bcmul(a, e) + bcmul(b, e)) / e
}

// 减法精度计算
export const bcsub = (a, b) => {
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length
	} catch (f) {
		c = 0
	}
	try {
		d = b.toString().split(".")[1].length
	} catch (f) {
		d = 0
	}
	return e = Math.pow(10, Math.max(c, d)), (bcmul(a, e) - bcmul(b, e)) / e
}

// 乘法精度计算
export const bcmul = (a, b) => {
	var c = 0,
		d = a.toString(),
		e = b.toString();
	try {
		c += d.split(".")[1].length
	} catch (f) {}
	try {
		c += e.split(".")[1].length
	} catch (f) {}
	return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c)
}

// 除法精度计算
export const bcdiv = (a, b) => {
	var c, d, e = 0,
		f = 0;
	try {
		e = a.toString().split(".")[1].length
	} catch (g) {}
	try {
		f = b.toString().split(".")[1].length
	} catch (g) {}
	return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), bcmul(c / d, Math
		.pow(10, f - e))
}

export const imageOss = (url, w = 120, h = 120, modenum = 2, type = '', format = 'jpg', resize = 'resize', multiple =
	3) => {
	let image = '';
	let mode = ["m_lfit", "m_mfit", "m_fill", "m_fixed"];
	// 图像，自适应方向：1，渐进显示：1，转换格式：jpg，图片质量：q_90，图片锐化：50，浓缩图
	let rule = ["?x-oss-process=image", "auto-orient,1", "interlace,1", "format,jpg", "quality,q_90", "sharpen,50",
		"resize,m_fixed,w_120,h_120"
	];
	// 转换格式
	if (format == 'png') {
		rule[3] = ["format", "png"].join(",");
	}
	// 判断是否有高度
	if (w == 0) {
		rule[6] = [resize, mode[modenum], `h_${h * multiple}`].join(",");
	} else if (h == 0) {
		rule[6] = [resize, mode[modenum], `w_${w * multiple}`].join(",");
	} else {
		rule[6] = [resize, mode[modenum], `w_${w * multiple}`, `h_${h * multiple}`].join(",");
	}
	//当地址不存在
	if (url) {
		if ((/^data:image\//.test(url))) {
			image = url;
		} else if ((/^(http|https):\/\/.+/.test(url))) {
			rule.pop();
			image = type == 'video' ? url : (url + rule.join("/"));
		} else {
			image = type == 'video' ? (config.baseUrl + url) : (config.baseUrl + url + rule.join("/"));
		}
	} else {
		if (type == 'transparent') {

		} else if (type == 'avatar') {
			image = require('@/static/mall/mine_def_touxiang_3x.png');
		} else {
			image = require('@/static/mall/img_default3x.png');
		}
	}
	return image;
}

// 赋值
export const pageckForIn = (ar1, ar2) => {
	Object.keys(ar1).forEach(key => {
		ar1[key] = ar2[key]
	})
	return ar1
}
